#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SeqListInit(SL* s)
{
	assert(s);
	SeqDatatype* tmp= (SeqDatatype*)malloc(sizeof(SeqDatatype) * 4);
	if (tmp == NULL)
	{
		perror("malloc is fail");
		return;
	}
	s->arr = tmp;
	s->size = 0;
	s->capacity = 4;
}

void SeqDestroy(SL* s)
{
	assert(s);
	free(s->arr);
	s->arr = NULL;
	s->capacity = 0;
	s->size = 0;
}

static void Check_Capacity(SL* s)
{
	assert(s);
	if (s->size == s->capacity)
	{
		SeqDatatype* tmp = (SeqDatatype*)realloc(s->arr, sizeof(SeqDatatype) * s->capacity * 2);
		if (tmp == NULL)
		{
			perror("malloc is fail");
			return;
		}
		s->arr = tmp;
		s->capacity *= 2;
	}
}

void SeqPushBack(SL* s,SeqDatatype x)
{
	assert(s);
	/*Check_Capacity(s);
	s->arr[s->size] = x;
	s->size++;*/
	SeqInsert(s, s->size, x);
}

void SeqPrint(SL* s)
{
	assert(s);
	for (int i = 0; i < s->size; i++)
	{
		printf("%d ", s->arr[i]);
	}
	printf("\n");
}

void SeqPushFront(SL* s, SeqDatatype x)
{
	assert(s);
	/*Check_Capacity(s);
	int end = s->size;
	while (end > 0)
	{
		s->arr[end] = s->arr[end-1];
		end--;
	}
	s->arr[0] = x;
	s->size++;*/
	SeqInsert(s, 0, x);
}

void SeqPopBack(SL* s)
{
	assert(s);
	assert(s->size > 0);

	s->size--;
}

void SeqPopFront(SL* s)
{
	assert(s);
	assert(s->size > 0);
	int start = 0;
	while (start < s->size - 1)
	{
		s->arr[start] = s->arr[start + 1];
		start++;
	}
	s->size--;
}

void SeqInsert(SL* s, int pos, SeqDatatype x)
{
	assert(s);
	assert(pos >= 0 && pos <= s->size);
	Check_Capacity(s);
	int end = s->size;
	while (end > pos)
	{
		s->arr[end] = s->arr[end - 1];
		end--;
	}
	s->arr[pos] = x;
	s->size++;

}

void SeqErase(SL* s, int pos)
{
	assert(s);
	assert(s->size > 0);
	assert(pos >= 0 && pos < s->size);
	int ptr = pos;
	while (ptr < s->size - 1)
	{
		s->arr[ptr] = s->arr[ptr + 1];
		ptr++;
	}
	s->size--;
}

int SeqFind(SL* s, SeqDatatype x)
{
	assert(s);
	assert(s->size > 0);
	int start = 0;
	while (start < s->size)
	{
		if (s->arr[start] == x)
		{
			return start;
		}
		start++;
	}
	return -1;
}

void SeqModify(SL* s, int pos, SeqDatatype x)
{
	assert(s);
	assert(s->size > 0);
	assert(pos >= 0 && pos <= s->size);

	s->arr[pos] = x;
}
